package com.tiancheng.trade.settlement.controller.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.settlement.bo.SettlementBillDataBO;
import com.tiancheng.trade.settlement.service.settlement.ISettlementBillDataService;
import com.tiancheng.trade.settlement.util.ObjectConvertUtil;
import com.tiancheng.trade.settlement.vo.settlement.api.SettlementBillDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 账单接收
 *
 * @author wx
 */
@RestController
@RequestMapping("/api/settlement")
@Validated
@Slf4j
public class SettlementBillDataController {
    @Resource
    private ISettlementBillDataService settlementService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 接收核销与退款账单（http方式调用）
     *
     * @param verifications
     * @return
     */
    @PostMapping(value = "/saveBill", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result saveBill(@RequestBody @Valid List<SettlementBillDataVO> verifications) throws JsonProcessingException {
        log.info("订单中心调用接口 saveVerificationBasic{}", objectMapper.writeValueAsString(verifications));
        // 生成主订单业务对象
        List<SettlementBillDataBO> verificationBOs = this.toSettlementBillDataBO(verifications);
        try {
            settlementService.saveBill(verificationBOs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    private List<SettlementBillDataBO> toSettlementBillDataBO(List<SettlementBillDataVO> verifications) {
        List<SettlementBillDataBO> verificationBOs = new ArrayList<SettlementBillDataBO>();
        for (SettlementBillDataVO vo : verifications) {
            SettlementBillDataBO orderBO = ObjectConvertUtil.convert(vo, SettlementBillDataBO.class).get();
            verificationBOs.add(orderBO);

        }
        return verificationBOs;
    }
}
